package com.niit.drugsmanager.controller;

import com.niit.drugsmanager.entity.User;
import com.niit.drugsmanager.service.UserService;
import com.niit.drugsmanager.utils.SessionUtils;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;


@Controller
@RequestMapping("/api/permission")
public class PermissionController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String permissionManagement(
            @RequestParam(value = "search", required = false) String search,
            @PageableDefault(size = 5) Pageable pageable,  // 固定每页5个用户
            HttpSession session,
            RedirectAttributes redirectAttributes,
            Model model) {
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        //权限检查
        boolean flag1 = user.hasRole(0b1001);
        boolean flag2 = user.hasPermission(0b0001);
        if(!(flag1 && flag2)) return "redirect:/api/user/non-permission";

        Page<User> userPage = userService.findUsers(search, pageable);
        model.addAttribute("page", userPage); // 传递Page对象到前端
        model.addAttribute("content", userPage.getContent());
        model.addAttribute("search", search); // 保留搜索条件
        return "/permission/index";
    }

    @PostMapping("/delete")
    public String deleteUser(
            @RequestParam(value = "userId") Long uid,
            HttpSession session,
            RedirectAttributes redirectAttributes){
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        User userById = userService.getUserById(uid);
        //权限检查
        boolean flag0 = user.hasRole(0b0101) && (!userById.hasRole(0b0100) && !userById.hasRole(0b1000));
        boolean flag1 = user.hasRole(0b1001) && (!userById.hasRole(0b1000) || (userById.getId() == user.getId()));
        boolean flag2 = user.hasPermission(0b0001);
        if(!((flag0 || flag1) && flag2)) return "redirect:/api/user/non-permission";
        if(!user.hasRole(0b0001)) return "redirect:/api/user/ban";


        boolean result = userService.removeUser(uid);
        if(result){
            redirectAttributes.addFlashAttribute("successMessage", "用户删除成功");
        }else {
            redirectAttributes.addFlashAttribute("errorMessage", "删除失败");
        }
        return "redirect:/api/permission";
    }

    @PostMapping("/update")
    public String updateUser(
            @RequestParam(value = "userId") Long uid,
            @RequestParam(value = "permissions", required = false) List<Integer> permissions,
            @RequestParam(value = "roles", required = false) List<Integer> roles,
            HttpSession session,
            RedirectAttributes redirectAttributes,
            Model model){
        //登录检查
        User user = (User) session.getAttribute("user");
        String s = SessionUtils.ifUserNull(user, userService);
        if(s != null) return s;

        User userById = userService.getUserById(uid);
        //权限检查
        boolean flag0 = user.hasRole(0b0101) && (!userById.hasRole(0b0100) && !userById.hasRole(0b1000));
        boolean flag1 = user.hasRole(0b1001) && (!userById.hasRole(0b1000) || (userById.getId() == user.getId()));
        boolean flag2 = user.hasPermission(0b0001);
        if(!((flag0 || flag1) && flag2)) return "redirect:/api/user/non-permission";

        int permission = 0;
        int role = 0;
        if(permissions != null){
            for (Integer i : permissions) {
                permission |= i;
            }
        }
        if(roles != null){
            for (Integer i : roles) {
                role |= i;
            }
        }
        try {
            User result = userService.updatePermissionAndRole(uid, permission, role);
            if(result!=null){
                redirectAttributes.addFlashAttribute("successMessage", "更新权限成功");
            }else {
                redirectAttributes.addFlashAttribute("errorMessage", "更新错误");
            }
        }catch (Exception e){
            redirectAttributes.addFlashAttribute("errorMessage", "更新失败" + e.getMessage());
        }
        return "redirect:/api/permission";
    }
}
